package Model.xml;

import Controller.ActionManager;
import Model.StatusMessage;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

/**
 * Template Design pattern
 * @author pieterc
 */
public abstract class XMLHandler implements ContentHandler {

    private String currentElement;
    private String currentText = "";

    protected abstract String getStatusTagName();

    protected abstract String getUserTagName();

    public XMLHandler() {
    }

    public void setDocumentLocator(Locator locator) {
    }

    public void startDocument() throws SAXException {
    }

    public void endDocument() throws SAXException {
    }

    public void startPrefixMapping(String prefix, String uri) throws SAXException {
    }

    public void endPrefixMapping(String prefix) throws SAXException {
    }

    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
    }

    public void processingInstruction(String target, String data) throws SAXException {
    }

    public void skippedEntity(String name) throws SAXException {
    }

    protected abstract void startUser();

    protected abstract void startStatus();

    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        currentElement = qName;
        currentText = "";
        if (qName.equals(getUserTagName())) {
            startUser();
        } else if (qName.equals(getStatusTagName())) {
            startStatus();
        }
    }

    protected abstract void handleElement(String elementName, String content);
    protected abstract StatusMessage getFinalStatusMessage();
    protected abstract void endUser();

    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals(getStatusTagName())) {
            ActionManager.getRemote().addStatus(getFinalStatusMessage());
        }else if (qName.equals(getUserTagName())) {
            endUser();
        }else{
            handleElement(currentElement, currentText);
        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        String text = new String(ch, start, length);
        text.trim();
        currentText += text;
        currentText.trim();
    }
}
